package com.achun.getcouponleague.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.achun.getcouponleague.Bean.SearchRecommend;
import com.achun.getcouponleague.Bean.SearchResult;
import com.achun.getcouponleague.R;
import com.achun.getcouponleague.base.BaseFragment;
import com.achun.getcouponleague.base.IRecyclerList;
import com.achun.getcouponleague.presenter.impl.SearchPresenter;
import com.achun.getcouponleague.presenter.impl.TiketPresenter;
import com.achun.getcouponleague.ui.activity.TiketActivity;
import com.achun.getcouponleague.ui.adapter.RecycleviewAdapter;
import com.achun.getcouponleague.ui.custom.FlowTextLayout;
import com.achun.getcouponleague.utils.Logutils;
import com.achun.getcouponleague.utils.PresenterManager;
import com.achun.getcouponleague.view.ISearchCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class Search_Fragment extends BaseFragment implements ISearchCallBack {
    @BindView(R.id.search_edit)
    public EditText searchEdit;
    public SearchPresenter searchPresenter;
    @BindView(R.id.iv_del_text)
    public ImageView DelText;
    @BindView(R.id.tv_go_search)
    public TextView GOSearch;
    @BindView(R.id.history_text_container)
    public LinearLayout historyTextContainer;
    @BindView(R.id.tv_del_search_histroy)
    public ImageView DelSearchHistory;
    @BindView(R.id.history_text_layout)
    public FlowTextLayout flowTextLayout;
    @BindView(R.id.recommend_text_container)
    public LinearLayout recommendTextContainer;
    @BindView(R.id.recommend_text)
    public FlowTextLayout recommendText;
    @BindView(R.id.search_list)
    public RecyclerView searchList;
    private RecycleviewAdapter recycleviewAdapter;
    private boolean isSearched=false;
    private TiketPresenter tiketPresenter;


    @Override
    protected void onReTry() {

    }

    @Override
    public View loadSuccessView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_search_success,container,false);
    }
    @Override
    protected View createRootView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_search,container,false);
    }

    @Override
    protected void initPresenter() {
        searchPresenter = PresenterManager.getInstance().getSearchPresenter();
        tiketPresenter = PresenterManager.getInstance().getTiketPresenter();
        searchPresenter.registerCallback(this);
        searchPresenter.getHisgory();
        searchPresenter.getRecommendWords();
    }

    @Override
    protected void initListener() {
        //键盘搜搜事件
        searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i== EditorInfo.IME_ACTION_SEARCH&&searchPresenter!=null){
                    //拿到内容
                    String searchWord = textView.getText().toString().trim();
                    //发起搜搜
                    searchPresenter.doSearch(searchWord);
                }
                return false;

            }
        });
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //输入监听
                DelText.setVisibility(View.VISIBLE);
                GOSearch.setText("搜索");
                isSearched=false;
                if (TextUtils.isEmpty(charSequence)){
                    GOSearch.setText("取消");
                    isSearched=true;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        //取消输入
        DelText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchEdit.setText("");
                DelText.setVisibility(View.GONE);
            }
        });
        //搜索点击事件
        GOSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isSearched){
                  searchList.setVisibility(View.GONE);
                  recommendTextContainer.setVisibility(View.VISIBLE);
                  GOSearch.setText("搜索");
                  isSearched=false;
                  searchPresenter.getHisgory();
                }else {
                    searchPresenter.doSearch(searchEdit.getText().toString().trim());
                }
            }
        });
        //列表项点击事件
        recycleviewAdapter.setRecycleViewOnClickListener(new RecycleviewAdapter.RecycleViewOnClickListener() {
            @Override
            public void onclick(int position, IRecyclerList item) {
                handleclick(item);
            }
        });
        //清除历史记录
        DelSearchHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchPresenter.deleteHisgory();
                searchPresenter.getHisgory();
            }
        });


    }
    //处理跳转事件
    private void handleclick(IRecyclerList item){
        String coupon_share_url = "https:"+item.getCoupon_share_url();
        String title = item.getTitle();
        String cover = item.getPict_url();
        tiketPresenter.createTiketCode(coupon_share_url,title,cover);
        Intent intent = new Intent(getContext(), TiketActivity.class);
        startActivity(intent);
    }
    @Override
    protected void initView(View rootview) {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        searchList.setLayoutManager(linearLayoutManager);
        recycleviewAdapter = new RecycleviewAdapter();
        searchList.setAdapter(recycleviewAdapter);

    }

    @Override
    protected void release() {
        searchPresenter.unRegisterCallback(this);
    }

    @Override
    public void onLoading() {
        setViewStatus(Status.LOADING);
    }

    @Override
    public void onError() {
setViewStatus(Status.ERROR);
    }

    @Override
    public void onEmpty() {
setViewStatus(Status.EMPTY);
    }

    @Override
    public void onLoadHisgroy(List<String> hisgorylist) {
        if (hisgorylist==null||hisgorylist.size()==0){
            historyTextContainer.setVisibility(View.GONE);

        }else {
            historyTextContainer.setVisibility(View.VISIBLE);
            Logutils.e(this.getClass(),"历史记录--"+hisgorylist);
            flowTextLayout.setTextList(hisgorylist);
            flowTextLayout.setOnFlowItemClickListener(new FlowTextLayout.OnFlowItemClickListener() {
                @Override
                public void onItemclick(String item) {
                  //  Toast.makeText(getContext(),"你点击了"+item,Toast.LENGTH_SHORT).show();
                    searchEdit.setText(item);
                    searchPresenter.doSearch(item);
                }
            });
        }

    }

    @Override
    public void onLoadSearchResult(SearchResult searchResult) {
        setViewStatus(Status.SUCCESS);
        GOSearch.setText("取消");
        isSearched=true;
    Logutils.e(this.getClass(),"搜索数据为--"+searchResult);
        List<SearchResult.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> map_data = searchResult.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data();
        recycleviewAdapter.setDatas(map_data);
        searchList.setVisibility(View.VISIBLE);
        historyTextContainer.setVisibility(View.GONE);
        recommendTextContainer.setVisibility(View.GONE);
    }

    @Override
    public void onLoadMoreResult(SearchResult searchResult) {

    }

    @Override
    public void onLoadMoreError() {

    }

    @Override
    public void onLoadMoreEmpty() {

    }

    @Override
    public void onLoadRecommend(SearchRecommend searchRecommend) {
        setViewStatus(Status.SUCCESS);
        List<SearchRecommend.DataBean> data = searchRecommend.getData();
        Logutils.e(this.getClass(),"页面加载推荐--》"+data);
        List<String> recommends=new ArrayList<>();
        for (SearchRecommend.DataBean datum : data) {
            recommends.add(datum.getKeyword());
        }
        if (recommends.size()!=0){
            recommendTextContainer.setVisibility(View.VISIBLE);
            recommendText.setTextList(recommends);
            recommendText.setOnFlowItemClickListener(new FlowTextLayout.OnFlowItemClickListener() {
                @Override
                public void onItemclick(String item) {
                   // Toast.makeText(getContext(),"你点击了"+item,Toast.LENGTH_SHORT).show();
                    searchEdit.setText(item);
                    searchPresenter.doSearch(item);
                }
            });
        }else {
            recommendTextContainer.setVisibility(View.GONE);
        }
    }
}